import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  UseInterceptors,
  UploadedFile,
  Request,
  Query,
  Redirect,
  Catch,
  UploadedFiles,
  Inject,
} from '@nestjs/common';
import { AppService } from './app.service';
import { ApiTags, ApiResponse } from '@nestjs/swagger';
import {
  AppRequestDTO,
  AppInfoDTO,
  AppRequestListDTO,
  AppSubmitDTO,
  AppRequestLateWithTypeDTO,
} from '../db/model/app.dto';
import {
  CommonResponse,
  CommonResCode,
  AppUploadFileDTO,
} from '../db/model/response.dto';
import {
  FileInterceptor,
  FileFieldsInterceptor,
} from '@nestjs/platform-express';
import AppEntity from '../db/entity/app.entity';
import FileEntity from '../db/entity/file.entity';
import { ClientProxy } from '@nestjs/microservices';

@Controller('app')
@ApiTags('app')
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject('server-publish') private readonly client: ClientProxy,
  ) {}

  @Get('/test')
  test() {
    let url =
      'http://s3-cn-east-1.qiniucs.com/file-mi/app-armeabi-v7a-release.apk?X-Amz-Algorithm=' +
      'AWS4-HMAC-SHA256&X-Amz-Credential=m1syJtZt97vSWT6sPrIce_dTRACwFtBViffPbIVA%2F20200503%2Fcn-east' +
      '-1%2Fs3%2Faws4_request&X-Amz-Date=20200503T123302Z&X-Amz-Expires=60000&X-Amz-Signature=90048d3f' +
      '2b6751fa0f45c4ce638b1f48fe9af66e9ab3479b6e3af68344f33cfb&X-Amz-SignedHeaders=host';
    return this.client.send('app-info-message', { url, type: 0 });
  }
  @Get('/id/:id')
  async getAppInfoWithId(@Param() params) {
    const entity = await AppEntity.findOne(params.id, { relations: ['file'] });
    return entity;
  }

  @Get('/removeApp/:id')
  async removeAppWithId(@Param() params) {
    try {
      await AppEntity.delete(params.id);
      return new CommonResponse(CommonResCode.Ok, '', '删除成功');
    } catch (e) {
      return new CommonResponse(CommonResCode.FileError, e, '删除失败');
    }
  }

  @Get('/latestWithType')
  async latestWithType(@Query() query: AppRequestLateWithTypeDTO) {
    const params = { ...query };
    const v = await AppEntity.findAndCount({
      where: { ...params },
      take: 1,
      relations: ['file'],
      order: { id: -1 },
    });
    const resObj = new CommonResponse(CommonResCode.Ok, v, 'success');
    return resObj;
  }

  @Get('/appList')
  async getAppList(@Query() query: AppRequestListDTO) {
    const params = { ...query };
    const v = await AppEntity.findAndCount({
      where: { ...params },
      take: params.pageSize || 100,
      relations: ['file'],
      order: { id: -1 },
    });
    const resObj = new CommonResponse(CommonResCode.Ok, v, 'success');
    return resObj;
  }

  @Post('/submitApp')
  @ApiResponse({ type: AppEntity })
  submitApp(@Body() param: AppSubmitDTO) {
    return this.appService.submitApp(param);
  }

  @Post('/uploadFile')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @Body() body: AppRequestLateWithTypeDTO,
    @UploadedFile() file,
  ): Promise<CommonResponse<FileEntity>> {
    return this.appService.uploadFile(body, file);
  }

  @Post('/uploadFiles')
  @UseInterceptors(
    FileFieldsInterceptor([
      { name: 'file', maxCount: 1 },
      { name: 'plist', maxCount: 1 },
    ]),
  )
  async uploadFiles(@Body() body, @UploadedFiles() files) {
    return this.appService.uploadFiles(files);
  }
}
